<?php

namespace App\Http\Controllers\Pc;

use App\Http\Requests\ProductRequest;
use App\Libs\platformApi\Lazada;
use App\Libs\wrapper\Vova;
use App\Libs\wrapper\Wish;
use App\Models\Shop;
use Illuminate\Http\Request;
use App\Http\Controllers\Jobs\NewProductController;

// 数据库
use Illuminate\Support\Facades\DB;

use App\Http\Controllers\Controller;
use think\validate\ValidateRule;

class ProductController extends Controller
{
//////////////////////////////////////////////// 商品
    private $model;
    private $request;

    public function __construct(ProductRequest $request = null)
    {
        $this->model = new \App\Models\ProductModel();
        $this->request = $request;
    }

    /**
     * 表格列表
     */
    public function getList()
    {
        $params = $this->request->all();
        $result = $this->model->getList($params);
        return $this->back('获取成功', '200', $result);
    }

    /**
     * 更新wish产品主sku
     */
    public function updateWishParentProduct()
    {
        $this->validate($this->request, [
            'product_id' => 'required| numeric',
            'name' => 'required| string',
            'desc' => 'required| string',
            //  'tags' => 'required| string',
            'sku' => 'required| string',
            'main_image' => 'required| string'
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误',
            'name.required' => '请填写产品名',
            'name.string' => '产品名必须是字符串',
            'desc.required' => '请填写产品描述',
            'desc.string' => '产品描述必须是字符串',
            //   'tags.required' => '请填写产品标签',
            //   'tags.string' => '产品标签必须是字符串',
            'sku.required' => '请填写sku',
            'sku.string' => 'sku必须是字符串',
            'main_image.required' => '请上传产品主图',
            'main_image.string' => '产品主图链接必须是字符串',
        ]);
        $params = $this->request->all();
        //先查询产品基本信息
        $productId = $params['product_id'];
        $sql = "select * from product where Id = $productId limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        $shopId = $product->shop_id;
        //平台产品id
        $platformProductId = $product->product_id_pt;
        $oldSku = $product->parent_sku;
        //查询access_token
        $sql = "select Id,access_token from shop where Id = $shopId limit 1";
        $shop = DB::select($sql);
        if (empty($shop)) {
            return $this->back('根据商户id查询没有结果~,请检查商户id');
        }
        $accessToken = $shop[0]->access_token;
        $name = $params['name'];
        $desc = $params['desc'];
        //  $tags = $params['tags'];
        $sku = $params['sku'];
        $mainImage = $params['main_image'];
        $obj = new \App\Libs\platformApi\Wish();
        $errors = [];
        //产品名 产品描述
        if (md5($product->product_name . $product->product_description . $product->main_image) != md5($name . $desc . $mainImage)) {
            $result = $obj->updateProduct($accessToken, $platformProductId, $name, $desc, $mainImage);
            if ($result['code'] == 0) {
                DB::beginTransaction();
                try {
                    $sql = "update product set product_name = '$name', product_description = '$desc', main_image = '$mainImage' where Id = $productId";
                    DB::update($sql);
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    $errors['SqlError'][] = $e->getMessage();
                }
            } else {
                $errors['platformError'][] = $result['message'];
            }
        }
        //父sku
        if (md5($oldSku) != md5($sku)) {
            $result = $obj->changeSku($accessToken, $oldSku, $sku);
            if ($result['code'] == 0) {
                DB::beginTransaction();
                try {
                    $sql = "update product set parent_sku = '$sku' where Id = $productId";
                    DB::update($sql);
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    $obj->changeSku($accessToken, $sku, $oldSku);
                    $errors['SqlError'][] = $e->getMessage();
                }
            } else {
                $errors['platformError'][] = $result['message'];
            }
        }
        if (empty($errors)) {
            return $this->back('更新成功', 200);
        }
        return $this->back($errors);
    }

    //wish启用产品与禁用
    public function wishProductInStatus()
    {
        $this->validate($this->request, [
            'product_id' => 'required| numeric',
            'status' => 'required| numeric',
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误',
            'status.required' => '缺少status参数',
            'status.numeric' => 'status类型错误',
        ]);
        $params = $this->request->all();
        //查询主产品基本信息
        $productId = $params['product_id'];
        $sql = "select * from product where Id = $productId limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        $shopId = $product->shop_id;
        //平台产品id
        $platformProductId = $product->product_id_pt;
        //查询access_token
        $sql = "select Id,access_token from shop where Id = $shopId limit 1";
        $shop = DB::select($sql);
        if (empty($shop)) {
            return $this->back('根据商户id查询没有结果~,请检查商户id');
        }
        $accessToken = $shop[0]->access_token;
        $status = $params['status'];
        $obj = new \App\Libs\platformApi\Wish();
        if ($status == 1) {
            //上架
            $result = $obj->enableProduct($accessToken, $platformProductId);
        } else {
            $result = $obj->disableProduct($accessToken, $platformProductId);
        }
        if ($result['code'] == 0) {
            DB::beginTransaction();
            try {
                $sql = "update product set is_on_sale = $status where Id = $productId";
                DB::update($sql);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result['message'];
        }
        if (empty($errors)) {
            return $this->back('更新成功', 200);
        }
        return $this->back($errors);
    }

    //vova 更新
//    public function vovaUpdateSpu(){
//        $this->validate($this->request, [
//            'product_id' => 'required| numeric',
//            'type' => 'required| string',  //更改的sku类型，只有两种:父sku(parent_sku),子sku(sku)
//            'new_parent_sku' => 'string',
//            'child_sku_id' => 'numeric',
//            'new_sku' => 'string',
//        ], [
//            'product_id.required' => '缺少product_id参数',
//            'product_id.numeric' => 'product_id类型错误',
//            'type.required' => '缺少type参数',
//            'type.string' => 'type类型错误',
//            'new_parent_sku.string' => 'new_parent_sku类型错误',
//            'child_sku_id.numeric' => 'child_sku_id类型错误',
//            'new_sku.string' => 'new_sku类型错误',
//        ]);
//        $params = $this->request->all();
//        //先查询产品基本信息
//        $productId = $params['product_id'];
//        $sql = "select p.product_id_pt,s.access_token,p.parent_sku from product p join shop s on p.shop_id = s.Id where p.Id = $productId limit 1";
//        $product = DB::select($sql);
//        if (empty($product)) {
//            return $this->back('根据产品id查询没有结果~,请检查产品id');
//        }
//        $product = $product[0];
//        //平台产品id
//        $platformProductId = $product->product_id_pt;
//        $accessToken = $product->access_token;
//        $type = $params['type'];
//        //更新主sku
//        if ($type == 'parent_sku' && !empty($params['new_parent_sku'])) {
//            //对比是否更改
//            if ( md5($product->parent_sku) == md5($params['new_parent_sku'])) {
//                return $this->back('更新成功',200);
//            }
//            $params = [
//                'product_id' => $platformProductId,
//                'type' => 'parent_sku',
//                //新的父sku，注意：更新父sku时，才有这个属性，如 [‘goods_id’ => ‘xxx’,’type’ => ‘parent_sku’,’new_parent_sku’ => ‘xxx’]
//                'new_parent_sku' => $params['new_parent_sku']
//            ];
//        } else if ($type == 'sku' && !empty($params['child_sku_id']) && !empty($params['new_sku'])) {
//            //更新子sku
//            $sql = "select goods_sku from product_sku where Id = {$params['child_sku_id']} limit 1";
//            $productSku = DB::select($sql);
//            if (empty($productSku)) {
//                return $this->back('根据child_sku_id为空,请检查参数');
//            }
//            $childSkuId = $params['child_sku_id'];
//            $newSku = $params['new_sku'];
//            $productSku = $productSku[0];
//            //对比是否更改
//            if ( md5($productSku->goods_sku) == md5($newSku)) {
//                return $this->back('更新成功',200);
//            }
//
//            $params = [
//                'product_id' => $platformProductId,
//                'type' => 'sku',
//                //旧的子sku，注意：更新子sku时，才有这个属性，如 [‘goods_id’ => ‘’,’type’ => ‘sku’,’goods_sku’ => ‘’,’new_sku’ => ‘’,’parent_sku’ => ‘’]
//                'goods_sku' => $productSku->goods_sku,
//                //新的子sku，注意：更新子sku时，才有这个属性
//                'new_sku' => $params['new_sku']
//            ];
//        } else {
//            $desc = '缺少必要参数';
//            if ($type == 'parent_sku') {
//                $desc .= 'new_parent_sku';
//            } else {
//                $desc .= 'child_sku_id,new_sku';
//            }
//            return $this->back($desc.'.请检查参数');
//        }
//        $obj = new Vova();
//        $result = $obj->updateGoodsData($accessToken,[],$params);
//        $errors = [];
//        if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
//            DB::beginTransaction();
//            try {
//                if ($type == 'parent_sku') {
//                    $sql = "update product set parent_sku = '{$params['new_parent_sku']}' where Id = $productId";
//                } else {
//                    $sql = "update product_sku set goods_sku = '{$params['new_sku']}' where Id = $childSkuId";
//                }
//                DB::update($sql);
//                DB::commit();
//            }catch (\Exception $e) {
//                DB::rollBack();
//                if ($type == 'sku') {
//                    $params['goods_sku'] = $newSku;
//                    $params['new_sku'] = $productSku->goods_sku;
//                    $obj->updateGoodsData($accessToken,[],$params);
//                }
//                $errors['SqlError'][] = $e->getMessage();
//            }
//        } else {
//            $errors['platformError'][] = $result['message'];
//        }
//        if (empty($errors)) {
//            return $this->back('更新成功',200);
//        }
//
//        return $this->back($errors);
//    }
    //vova平台spu更新
    public function vovaUpdateSpu()
    {
        $this->validate($this->request, [
            'product_id' => 'required| numeric',
            'new_parent_sku' => 'required| string',
            'product_name' => 'required|string',
            'product_description' => 'required|string',
            'cat_id' => 'required|string',
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误',
            'new_parent_sku.string' => 'new_parent_sku类型错误',
            'new_parent_sku.required' => '缺少new_parent_sku参数',
            'product_name.required' => '缺少product_name参数',
            'product_name.string' => 'product_name类型错误',
            'product_description.required' => '缺少product_description参数',
            'product_description.string' => 'product_description类型错误',
            'cat_id.required' => '缺少cat_id参数',
            'cat_id.string' => 'cat_id类型错误',
        ]);
        $params = $this->request->all();
        //先查询产品基本信息
        $productId = $params['product_id'];
        $sql = "select p.product_id_pt,s.access_token,p.parent_sku,p.product_name,p.product_description,p.cat_id from product p join shop s on p.shop_id = s.Id where p.Id = $productId limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        //平台产品id
        $platformProductId = $product->product_id_pt;
        $accessToken = $product->access_token;
        //更新主sku
        //对比是否更改
        $newParentSku = $params['new_parent_sku'];
        $productName = $params['product_name'];
        $productDescription = $params['product_description'];
        $catId = $params['cat_id'];
        $oldMd5 = $product->parent_sku . $product->product_name . $product->product_description . $product->cat_id;
        $newMd5 = $newParentSku . $productName . $productDescription . $catId;
        if (md5($oldMd5) == md5($newMd5)) {
            return $this->back('更新成功', 200);
        }
        $updateInfo = [
            'product_id' => $platformProductId,
            'type' => 'parent_sku',
            //新的父sku，注意：更新父sku时，才有这个属性，如 [‘goods_id’ => ‘xxx’,’type’ => ‘parent_sku’,’new_parent_sku’ => ‘xxx’]
            'new_parent_sku' => $newParentSku
        ];
        $obj = new \App\Libs\platformApi\Vova();
        $result = $obj->updateGoodsData($accessToken, [], $updateInfo);
        $errors = [];
        if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
            DB::beginTransaction();
            try {
                $sql = "update product set parent_sku = '$newParentSku' where Id = $productId";
                DB::update($sql);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result;
        }
        //名称
        $updateInfo = [
            'product_id' => $platformProductId,
            'value' => $productName
        ];
        $result = $obj->updateGoodsByType($accessToken, 'goods_name', $updateInfo);
        if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
            DB::beginTransaction();
            try {
                $sql = "update product set product_name = '$productName' where Id = $productId";
                DB::update($sql);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result;
        }

        //描述
        $updateInfo = [
            'product_id' => $platformProductId,
            'value' => $productDescription
        ];
        $result = $obj->updateGoodsByType($accessToken, 'goods_desc', $updateInfo);
        if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
            DB::beginTransaction();
            try {
                $sql = "update product set product_description = '$productDescription' where Id = $productId";
                DB::update($sql);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result;
        }

        //分类
        $updateInfo = [
            'product_id' => $platformProductId,
            'value' => $catId
        ];
        $result = $obj->updateGoodsByType($accessToken, 'goods_category', $updateInfo);
        if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
            DB::beginTransaction();
            try {
                $sql = "update product set cat_id = $catId where Id = $productId";
                DB::update($sql);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result;
        }

        if (empty($errors)) {
            return $this->back('更新成功', 200);
        }
        return $this->back($errors);
    }

    //vova平台spu商品上下架
    public function vovaGoodsSaleStatus()
    {
        $this->validate($this->request, [
            'product_id' => 'required| numeric',
            'status' => 'required| numeric',
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误',
            'status.required' => '缺少status参数',
            'status.numeric' => 'status类型错误',
        ]);
        $params = $this->request->all();
        //查询主产品基本信息
        $productId = $params['product_id'];
        $sql = "select * from product where Id = $productId limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        $shopId = $product->shop_id;
        //平台产品id
        $platformProductId = $product->product_id_pt;
        //查询access_token
        $sql = "select Id,access_token from shop where Id = $shopId limit 1";
        $shop = DB::select($sql);
        if (empty($shop)) {
            return $this->back('根据商户id查询没有结果~,请检查商户id');
        }
        $accessToken = $shop[0]->access_token;
        $status = $params['status'];
        $obj = new \App\Libs\platformApi\Vova();
        if ($status == 1) {
            //上架
            $result = $obj->enableSale($accessToken, $platformProductId);
        } else {
            $result = $obj->disableSale($accessToken, $platformProductId);
        }
        if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
            DB::beginTransaction();
            try {
                $sql = "update product set is_on_sale = $status where Id = $productId";
                DB::update($sql);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result;//$result['data']['errors_list']
        }
        if (empty($errors)) {
            return $this->back('更新成功', 200);
        }
        return $this->back($errors);
    }

    //lazada spu编辑
    public function lazadaSpuUpdate()
    {
        $this->validate($this->request, [
            'product_id' => 'required|numeric',
            'product_name' => 'required|string',
            'product_description' => 'required|string',
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误',
            'product_name.required' => '缺少product_name参数',
            'product_name.string' => '类型product_name错误',
            'product_description.required' => '缺少product_description参数',
            'product_description.string' => '类型product_description错误'
        ]);
        $params = $this->request->all();
        $productId = $params['product_id'];
        $sql = "select p.product_id_pt,p.product_name,p.product_description,s.access_token,ps.goods_sku 
                from product p 
                join product_sku ps on ps.product_id = p.Id
                join shop s on p.shop_id = s.Id
                where p.Id = $productId
                limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }

        $product = $product[0];
        $productName = $params['product_name'];
        $productDescription = $params['product_description'];
        if (md5($product->product_name . $product->product_description)
            == md5($productName . $productDescription)) {
            return $this->back('更改成功', 200);
        }
        $accessToken = $product->access_token;
        $platformProductId = $product->product_id_pt;
        $goodsSku = $product->goods_sku;
        $obj = new Lazada();
        $result = $obj->updateSpuProduct($accessToken, $platformProductId, $productName, $productDescription, $goodsSku);
        $errors = [];
        if (isset($result['code']) && $result['code'] == 0) {
            DB::beginTransaction();
            try {
                $sql = "update product set product_name = '$productName',product_description = '$productDescription' where Id = $productId";
                DB::update($sql);
                DB::commit();

            } catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result;
        }
        if (empty($errors)) {
            return $this->back('更新成功', 200);
        }
        return $this->back($errors);
    }



    /**
     * 条形码导出-仓库
     */

    public function barcode_export_ck(Request $request)
    {
        $data = $request->all();
        $call_product = new \App\Libs\wrapper\Product();
        $return = $call_product->barcode_export_ck($data);
    }
    /**
     * 条形码导出
     */

    public function barcode_export(Request $request)
    {
        $data = $request->all();
        $call_product = new \App\Libs\wrapper\Product();
        $return = $call_product->barcode_export($data);
    }

    //查询条形码信息

    /**
     * 表格列表
     */
    public function getBarcode()
    {
        $params = $this->request->all();
        $result = $this->model->getBarcode($params);
        return $this->back('获取成功', '200', $result);
    }


    //查询条形码信息-供应链专用

    /**
     * 表格列表
     */
    public function getBarcodeCk()
    {
        $params = $this->request->all();
        $result = $this->model->getBarcodeByCk($params);
        return $this->back('获取成功', '200', $result);
    }

    //查询条形码信息-仓库专用

    /**
     * 表格列表
     */
    public function getBarcodeWare()
    {
        $params = $this->request->all();
        $result = $this->model->getBarcodeWare($params);
        return $this->back('获取成功', '200', $result);
    }

    //订单出库 导入查询
    public function BarcodePlatformExcelImport()
    {
        $params = $this->request->all();

        if (empty($params['platform_id'])) {
            return $this->back('平台id不能为空');
        }
        if (empty($params['warehouse_id'])) {
            return $this->back('仓库id不能为空');
        }
        $result = $this->model->BarcodePlatformExcelImport($params);
        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back('获取失败'.$result['msg'], '300' );
        }
    }

    /**
     * 平台专用
     * 表格列表
     */
    public function getBarcodePlatform()
    {
        $params = $this->request->all();

        if (empty($params['platform_id'])) {
            return $this->back('平台id不能为空');
        }
        $result = $this->model->getBarcodePlatform($params);

        return $this->back('获取成功', '200', $result);
    }

        /**
     * 表格列表
     */
    public function getBarcodeCkNew()
    {
        $params = $this->request->all();
        $result = $this->model->getBarcodeByCkNew($params);
        return $this->back('获取成功', '200', $result);
    }

    /**
     * 修改条形码中英文名
     */
    public function updateBarcode()
    {
        $params = $this->request->all();
        $result = $this->model->updateBarcode($params);
        return $this->back($result['msg'], '200');
    }

    /**
     * 条形码导入查询
     */
    public function product_excel_export(Request $request)
    {
        $data = $request->all();
        $data['file'] = $_FILES['file'];
        if (empty($data['file'])) {
            $this->back('文件为空');
        }

        $call_product = new \App\Libs\wrapper\Product();
        $return = $call_product->product_excel_export($data);

        if (is_array($return)) {
            return $this->back('导入成功', '200', $return);
        } else {
            return $this->back('导入失败'.$return, '500');
        }
    }

    /**
     * 条形码导入查询
     */
    public function product_excel_export_ck(Request $request)
    {
        $params = $this->request->all();
        $result = $this->model->exportBarcodeCk($params);
        return $this->back('获取成功', '200', $result);
    }


    /**
     * 仓库调拨导入
     */
    public function BarcodeWareImport(Request $request)
    {
        $params = $this->request->all();
        $result = $this->model->BarcodeWareImport($params);
        return $this->back('获取成功', '200', $result);
    }


    
    /**
     * 仓库调拨导入-库存sku
     */
    public function BarcodeWareCusImport(Request $request)
    {
        $params = $this->request->all();
        $result = $this->model->BarcodeWareCusImport($params);
        if($result['type']=='success'){
            return $this->back('导入成功', '200', $result);
        }else{
            return $this->back($result['msg'], '500', $result);
        }

    }


    

    /**
     * 亚马逊sku
     * @param Request $request
     */
    public function amazon_sku($params)
    {
        if (!isset($params['shop_id'])) {
            return $this->back('没有shop_id参数', '300');
        }
        if (!isset($params['sku'])) {
            return $this->back('没有sku参数', '300');
        }

        $skuList = explode(",", $params['sku']);
        $Shop = Shop::where('id', $params['shop_id'])->first();

        $shop['auth'] = json_decode($Shop['app_data'], true);
        $auth = $shop['auth'];

        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'MarketplaceWebServiceProducts' . DIRECTORY_SEPARATOR . 'Client.php');
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'MarketplaceWebServiceProducts' . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . 'GetMatchingProductForIdRequest.php');
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'MarketplaceWebServiceProducts' . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . 'SellerSKUListType.php');
        $serviceUrl = "https://mws.amazonservices.com/Products/2011-10-01";
        // Europe
        $serviceUrl_eu = "https://mws-eu.amazonservices.com/Products/2011-10-01";
        // Japan
        $serviceUrl_jp = "https://mws.amazonservices.jp/Products/2011-10-01";

        if ($auth['MARKETPLACE_ID'] == 'A1VC38T7YXB528') $serviceUrl = $serviceUrl_jp;
        if (in_array($auth['MARKETPLACE_ID'], array('A1F83G8C2ARO7P', 'A1PA6795UKMFR9', 'A1RKKUPIHCS9HS', 'A13V1IB3VIYZZH', 'APJ6JRA9NG5V4'))) $serviceUrl = $serviceUrl_eu;

        $config = array(
            'ServiceURL' => $serviceUrl,
            'ProxyHost' => null,
            'ProxyPort' => -1,
            'ProxyUsername' => null,
            'ProxyPassword' => null,
            'MaxErrorRetry' => 3,
        );

        $service = new \MarketplaceWebServiceProducts_Client(
            $auth['AWS_ACCESS_KEY_ID'],
            $auth['AWS_SECRET_ACCESS_KEY'],
            'MarketplaceWebServiceProducts PHP5 Library',
            '2',
            $config);

        /************************************************************************
         * Uncomment to try out Mock Service that simulates MarketplaceWebServiceProducts
         * responses without calling MarketplaceWebServiceProducts service.
         *
         * Responses are loaded from local XML files. You can tweak XML files to
         * experiment with various outputs during development
         *
         * XML files available under MarketplaceWebServiceProducts/Mock tree
         *
         ***********************************************************************/
        // $service = new MarketplaceWebServiceProducts_Mock();

        /************************************************************************
         * Setup request parameters and uncomment invoke to try out
         * sample for Get Matching Product For Id Action
         ***********************************************************************/
        // @TODO: set request. Action can be passed as MarketplaceWebServiceProducts_Model_GetMatchingProductForId
        $request = new \MarketplaceWebServiceProducts_Model_GetMatchingProductForIdRequest();
        $request->setSellerId($auth['MERCHANT_ID']);
        $request->setMarketplaceId($auth['MARKETPLACE_ID']);
        if (isset($auth['MWSAuthToken'])) $request->setMWSAuthToken($auth['MWSAuthToken']);
        $request->setIdType('SellerSKU');
        $idlist = new \MarketplaceWebServiceProducts_Model_SellerSKUListType();
        $idlist->setSellerSKU($skuList);
        $request->setIdList($idlist);

        try {
            $response = $service->GetMatchingProductForId($request);
            $dom = new \DOMDocument();
            $dom->loadXML($response->toXML());
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            $str = $dom->saveXML();
            $str = str_replace('ns2:', '', $str);
            $xml = simplexml_load_string($str);
            return json_decode(json_encode($xml), true);
        } catch (\MarketplaceWebServiceProducts_Exception $ex) {
            echo("Caught Exception: " . $ex->getMessage() . "\n");
            echo("Response Status Code: " . $ex->getStatusCode() . "\n");
            echo("Error Code: " . $ex->getErrorCode() . "\n");
            echo("Error Type: " . $ex->getErrorType() . "\n");
            echo("Request ID: " . $ex->getRequestId() . "\n");
            echo("XML: " . $ex->getXML() . "\n");
            echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
        }

    }

    //亚马逊新品导入
    public function new_product_export(Request $request)
    {
        $params = $request->all();
        $params['file'] = $_FILES['file'];
        $user_id = $params['user_id'];
        if (empty($params['file'])) {
            $this->back('文件为空');
        }

        ////获取Excel文件数据
        //载入文档
        $objPHPExcelReader = \PHPExcel_IOFactory::load($params['file']['tmp_name']);
        $currentSheet = $objPHPExcelReader->getSheet(0);//读取第一个工作表(编号从 0 开始)
//		$allColumn = 'O';//取得总列数
        $allColumn = $currentSheet->getHighestColumn();//取得总列数
        $allRow = $currentSheet->getHighestRow();//取得总行数
        $add_list = array();
        /**从第1行开始输出*/
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $shop_id = '';
            $sku = '';
            /**从第A列开始输出*/
            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                $key = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), 1)->getValue();//数据键值
                $val = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getValue();//数据
                $gva = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getFormattedValue();//数据

                if ($currentColumn == 'C') {
                    break;
                }
                //判断键名是否正确
                $array_key = array('店铺id', 'sku');
                if (!in_array($key, $array_key)) {
//                    return 'Excel数据格式不对,请下载Excel模板进行导入';
                    return $this->back('Excel数据格式不对,请下载Excel模板进行导入', 500);
                }

                if ($key == '店铺id') {
                    $shop_id = $val;
//                    $add_list[$currentRow - 2]['shop_id'] = $val;
                } elseif ($key == 'sku') {
                    $sku = $val;
//                    $add_list[$currentRow - 2]['sku'] = $val;
                }

            }

            //判断店铺id和sku不为空
            if ($shop_id && $sku) {
                $add_list[$currentRow - 2]['shop_id'] = $shop_id;
                $add_list[$currentRow - 2]['sku'] = $sku;
            }

            if ($shop_id && !$sku) {
//                return '请填写sku';
                return $this->back('请填写sku', 500);
            }
            if (!$shop_id && $sku) {
//                return '请填写店铺id';
                return $this->back('请填写店铺id', 500);
            }
        }

        $add_list['user_id'] = $user_id;

 
        //调用队列
        $job = new NewProductController();
        try {
            $job::runJob($add_list);
        } catch(\Exception $e){
            return $this->back('导入队列失败', 500);
        }
        return $this->back('导入队列成功', 200);

//         $insert_product = '';
//         $insert_sku = '';
//         foreach ($add_list as $key => $value) {
//             //查询导入的sku在product_detail是否存在
//             $prodoct_detail = Db::table('product_detail')->where('sellersku', $value['sku'])->first();
//             //查询导入的sku在amazon_skulist是否存在
//             $amazon_skulist = Db::table('amazon_skulist')->where('sku', $value['sku'])->first();
//             $amazon_sku = $this->amazon_sku($value);
//             $data = $amazon_sku['GetMatchingProductForIdResult'];
//             if (isset($data['Error'])) {
// //                return $data['Error']['Message'] . ',请十分钟后再上传';
//                 return $this->back($data['Error']['Message'] . ',请十分钟后再上传', 500);

//             }
//             $parent_asin = $data['Products']['Product']['Relationships']['VariationParent']['Identifiers']['MarketplaceASIN']['ASIN']??'';
//             $asin = $data['Products']['Product']['Identifiers']['MarketplaceASIN']['ASIN']??'';
//             $itemAttributes = $data['Products']['Product']['AttributeSets']['ItemAttributes'];
//             $brand = $itemAttributes['Brand']??'';
//             $color = $itemAttributes['Color']??'';
//             $binding = $itemAttributes['Binding']??'';
//             $department = $itemAttributes['Department']??'';
//             $productGroup = $itemAttributes['ProductGroup']??'';
//             $productTypeName = $itemAttributes['ProductTypeName']??'';
//             $smallImage = $itemAttributes['SmallImage']['URL']??'';
//             $title = $itemAttributes['Title']??'';
//             $title = addslashes($title);
//             $size = $itemAttributes['Size']??'';
//             $time = time();
//             if (empty($prodoct_detail)) {
//                 $insert_product .= "('{$value['shop_id']}',5,'{$value['sku']}','{$parent_asin}','{$asin}','{$brand}','{$color}','{$binding}','{$department}','{$productGroup}','{$productTypeName}','{$smallImage}','{$title}','{$size}','{$time}',{$user_id},1),";
//             }
//             if (empty($amazon_skulist)) {
//                 $insert_sku .= "('{$value['shop_id']}','{$value['sku']}','{$asin}','{$time}','{$user_id}','{$parent_asin}'),";
//             }

//         }
//         //去除多余的逗号
//         $new_insert_product = substr($insert_product, 0, strlen($insert_product) - 1);
//         $new_insert_sku = substr($insert_sku, 0, strlen($insert_sku) - 1);
//         Db::beginTransaction();
//         try {
//             if (!empty($new_insert_product)) {
//                 $insert_product_sql = "INSERT INTO product_detail (
//                         `shop_id`,
//                         `platform_id`,
//                         `sellersku`,
//                         `parent_asin`,
//                         `asin`,
//                         `brand`,
//                         `color`,
//                         `binding`,
//                         `department`,
//                         `product_group`,
//                         `product_type_name`,
//                         `small_image`,
//                         `title`,
//                         `size`,
//                         `update_time`,
//                         `user_id`,
//                         `is_query`
//                     )
//                     VALUES
//                        {$new_insert_product}";
//                 $insert_product_res = Db::insert($insert_product_sql);
//             }
//             if (!empty($new_insert_sku)) {
//                 $insert_sku_sql = "INSERT INTO amazon_skulist (
//                         `shop_id`,
//                         `sku`,
//                         `asin`,
//                         `time`,
//                         `user_id`,
//                         `father_asin`   
//                     )
//                     VALUES
//                        {$new_insert_sku}";
//                 $insert_res = Db::insert($insert_sku_sql);
//             }
//             DB::commit();
//             $code = 200;
//             $msg = '导入成功';
//         } catch (\Exception $e) {
//             DB::rollBack();
//             $code = 500;
//             $msg = $e->getMessage();
//         }

//         return $this->back($msg, $code);
    }



    //亚马逊产品数据追踪表
    public function product_trace(){
        $params = $this->request->all();

        $result = $this->model->product_trace($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);

    }

    public function strategy_task(){
        $params = $this->request->all();

        $result = $this->model->strategy_task($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function saveSkuStrategy()
    {
        $params = $this->request->all();
        $result = $this->model->saveSkuStrategy($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }


    public function getStrategyByUser()
    {
        $params = $this->request->all();
        $result = $this->model->getStrategyByUser($params);
        return $this->back('获取成功','200',$result['data']);
    }
}
